package com.lms.demo.autoconfigure.minio;

import com.lms.demo.autoconfigure.ObjectStorage;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.ServerSideEncryptionCustomerKey;
import io.minio.errors.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.KeyGenerator;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-12-25 11:22
 * @Description:
 */
public class MinioTemplate implements ObjectStorage {
    private  MinioClient minioClient;

    public MinioTemplate(MinioProperties minioProperties) {
        this(minioProperties.getEndpoint(),minioProperties.getAccessKey(),minioProperties.getSecretKey());
    }

    public MinioTemplate(String endpoint, String accessKey, String secretKey) {
        minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    private PutObjectArgs buildPutObjectArgs(String buckName, String objectName, InputStream inputStream) throws IOException {
        return PutObjectArgs.builder()
                .bucket(buckName)
                .object(objectName)
                .stream(inputStream, inputStream.available(), -1)
                .build();
    }

    private GetObjectArgs buildGetObjectArgs(String buckName, String objectName) {
        return GetObjectArgs.builder().bucket(buckName).object(objectName).build();
    }

    @Override
    public void uploadObjectByInputStream(String buckName, String objectName, InputStream inputStream)
            throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
        minioClient.putObject(buildPutObjectArgs(buckName, objectName, inputStream));
    }

    @Override
    public void uploadObjectByMultipartFile(String buckName, String objectName, MultipartFile multipartFile) throws MinioException, IOException, InvalidKeyException, NoSuchAlgorithmException {
        try (InputStream inputStream = multipartFile.getInputStream()) {
            uploadObjectByInputStream(buckName, objectName, inputStream);
        }
    }

    @Override
    public void uploadObjectByBytes(String buckName, String objectName, byte[] content) throws MinioException, NoSuchAlgorithmException, InvalidKeyException, IOException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(content)) {
            uploadObjectByInputStream(buckName, objectName, bais);
        }
    }

    @Override
    public InputStream downloadByObjectName(String buckName, String objectName) throws MinioException, NoSuchAlgorithmException, InvalidKeyException, IOException {
        return minioClient.getObject(buildGetObjectArgs(buckName, objectName));
    }

}
